﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.IO;

namespace TextImageMerge
{
    public class JsonHelper
    {
        /// <summary>
        /// 通过文件路径获取json文件中的内容
        /// </summary>
        /// <param name="cfgFilePath">配置文件存储路径</param>
        /// <returns></returns>
        public static T ReadJson<T>(string cfgFilePath)
        {
            if (!File.Exists(cfgFilePath))
            {
                File.Create(cfgFilePath);
            }

            //读取json文件  
            using (StreamReader sr = new StreamReader(cfgFilePath))
            {
                try
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Converters.Add(new JavaScriptDateTimeConverter());
                    serializer.NullValueHandling = NullValueHandling.Ignore;
                    //构建Json.net的读取流  
                    JsonReader reader = new JsonTextReader(sr);
                    //对读取出的Json.net的reader流进行反序列化，并装载到模型中  
                    T t = serializer.Deserialize<T>(reader);
                    return t;
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }
            }
            return default;
        }

        /// <summary>
        /// 写Json数据到Json文件中
        /// </summary>
        /// <param name="cfgFilePath">配置文件的路径</param>
        /// <param name="cfgModel">配置类对象</param>
        /// <returns></returns>
        public static bool WriteJson<T>(T model, string cfgFilePath)
        {
            //判断文件是否存在
            if (!File.Exists(cfgFilePath))
            {
                StreamWriter sw = File.CreateText(cfgFilePath);
                sw.Close();
            }

            //把模型数据写到文件  
            using (StreamWriter sw = new StreamWriter(cfgFilePath))
            {
                try
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Converters.Add(new JavaScriptDateTimeConverter());
                    serializer.NullValueHandling = NullValueHandling.Ignore;
                    //构建Json.net的写入流  
                    JsonWriter writer = new JsonTextWriter(sw);
                    //把模型数据序列化并写入Json.net的JsonWriter流中  
                    serializer.Serialize(writer, model);
                    //ser.Serialize(writer, ht);  
                    writer.Close();
                    sw.Close();
                    return true;
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }
            }
            return false;
        }
    }
}
